package com.ybwh.springboot1.service;

import com.ybwh.springboot1.common.Constant;
import com.ybwh.springboot1.common.RespData;
import com.ybwh.springboot1.common.TokenInfo;
import com.ybwh.springboot1.model.po.User;
import com.ybwh.springboot1.model.vo.UserParamVo;
import com.ybwh.springboot1.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.ybwh.springboot1.dao.UserMapper;
import com.ybwh.springboot1.util.Md5Util;

import java.util.Objects;

/**
 * 用户模块
 */
@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	/**
	 * 登录,返回登录token
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @return null：登录失败，其他：登录令牌
	 */
	public RespData<String> doLogin(String username, String password) {
		Preconditions.checkNotNull(username);
		Preconditions.checkNotNull(password);

		String md5 = Md5Util.calcMd5(password);

		User user = userMapper.selectUser(username, md5);
		if (null == user) {
			return RespData.failedResp("用户名或密码错误！");
		}

		if (Objects.equals(Constant.YES, user.getDisabled())) {
			return RespData.failedResp("用户已被禁用！！");
		}

		TokenInfo tokenInfo = new TokenInfo(user.getUserName(), System.currentTimeMillis(), TokenInfo.DEFAULT_EXPIRE);
		return RespData.successResp(TokenUtil.encodeToken(tokenInfo));
	}

	/**
	 * 根据用户名查找用户信息
	 * 
	 * 
	 * @param username
	 * @return
	 */
	public User queryUserByUsername(String username) {
		Preconditions.checkNotNull(username);
		return userMapper.selectUser(username, null);
	}

	/**
	 * 分页查询
	 * 
	 * @param pageNum 页号
	 * @param pageSize 页大小
	 * @param param 查询参数
	 * @return
	 */
	public PageInfo<User> queryUserPage(int pageNum, int pageSize, UserParamVo param) {
		Page<User> pager = userMapper.selectByPageNumSize(param,pageNum, pageSize);
		return new PageInfo<>(pager);
	}

}
